﻿using System;
using System.Collections.Generic;
using System.Reflection;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using TeF.Runner.Common.Extensions;

namespace TeF.Runner.UI.Services
{
    internal class TreeViewManager : ITreeViewManager
    {
        private TreeView _treeView;
        
        private readonly HashSet<HierarchicalItemViewModel> _selectedItems = new HashSet<HierarchicalItemViewModel>();
        
        private static readonly PropertyInfo _isSelectionChangeActiveProperty = 
            typeof(TreeView).GetProperty("IsSelectionChangeActive", BindingFlags.NonPublic | BindingFlags.Instance);
        
        public IEnumerable<HierarchicalItemViewModel> SelectedItems
        {
            get { return _selectedItems; }
        }

        public void AllowMultiSelection(TreeView treeView)
        {
            if (treeView == null)
                throw new ArgumentNullException("treeView");
            
            _treeView = treeView;
            _treeView.SelectedItemChanged += TreeView_SelectedItemChanged;
        }

        private void TreeView_SelectedItemChanged(object sender, RoutedPropertyChangedEventArgs<object> e)
        {
            var treeViewItem = _treeView.SelectedItem as HierarchicalItemViewModel;
            if (treeViewItem == null)
                return;

            if (Keyboard.IsKeyDown(Key.LeftCtrl) || Keyboard.IsKeyDown(Key.RightCtrl))
            {
                var isSelectionChangeActive = _isSelectionChangeActiveProperty.GetValue(_treeView, null);

                _isSelectionChangeActiveProperty.SetValue(_treeView, true, null);

                _selectedItems.DoForEach(item => item.IsSelected = true);

                _isSelectionChangeActiveProperty.SetValue(_treeView, isSelectionChangeActive, null);
            }
            else
            {
                _selectedItems.DoForEach(item => item.IsSelected = (item == treeViewItem));
                _selectedItems.Clear();
            }

            if (!_selectedItems.Contains(treeViewItem))
            {
                _selectedItems.Add(treeViewItem);
            }
            else
            {
                treeViewItem.IsSelected = false;
                _selectedItems.Remove(treeViewItem);
            }

            FireSelectedItemsChanged();
        }
        
        public event EventHandler SelectedItemsChanged;

        private void FireSelectedItemsChanged()
        {
            if (SelectedItemsChanged != null)
                SelectedItemsChanged(this, EventArgs.Empty);
        }
    }
}
